/* Copyright (c) 2004-2022 peigen.info. All rights reserved. */

package info.peigen.hotpot.common.core.validator;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldDefaults;

/**
 * <b>(EmailValidator)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/7/31
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class EmailValidator implements ConstraintValidator<Email, String> {
    boolean nullable;
    boolean blankable;
    String  message;

    @Override
    public void initialize(Email email) {
        this.nullable = email.nullable();
        this.message = email.message();
        this.blankable = email.blankable();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (ObjectUtil.isNull(value)) {
            if (!this.nullable) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("Email地址不能为空").addConstraintViolation();
                return false;
            } else {
                return true;
            }
        } else if (StrUtil.isEmpty(value)) {
            if (!this.blankable) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("Email地址不能为空").addConstraintViolation();
                return false;
            } else {
                return true;
            }
        } else if (!Validator.isEmail(value)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Email格式非法").addConstraintViolation();
            return false;
        } else {
            return true;
        }
    }
}